package com.hk.asyncprocess.compensation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;

@RestController
@Slf4j
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 用户注册之后，会发欢迎消息，但是有一半的概率会失败，所以使用一个补偿定时任务，记录上次执行后的用户的id，
     * 然后对剩下的用户进行补偿执行
     */
    @GetMapping("register")
    public void register() {
        IntStream.rangeClosed(1,10).forEach(i -> {
            User user = userService.register();
            //有50%的消息可能会发送失败
            if (ThreadLocalRandom.current().nextInt(10) % 2 == 0){
                rabbitTemplate.convertAndSend(RabbitConfiguration.EXCHANGE,RabbitConfiguration.ROUTING_KEY, user);
                log.info("send mq user {}", user.getId());
            }
        });
    }




}
